package FillMythMetadataSubtitleDownloader;
use FillMythMetadataHttpCaller;
use strict;

my $subtitles_front_page_cache = '';
my $show_subtitles_name_cache = '';
my $show_subtitles_season_cache = '';
my $show_subtitles_show_id = '';
my $show_subtitles_page_cache = '';
sub download_tv_subtitle
{
	my $tv_show = $_[0];
	my $full_subtitle_filename = $_[1];
	my $season = $_[2];
	my $episode = $_[3];
	
	if ($episode < 10)
	{
		$episode = "0".$episode;
	}
	
	if (-e $full_subtitle_filename)
	{
		print "Subtitle exists.\n";
		return;
	}
	
	if ($subtitles_front_page_cache eq '')
	{
		my $url = "http://www.tvsubtitles.net/tvshows.html";

		$subtitles_front_page_cache = FillMythMetadataHttpCaller::get_http_response($url);
	}

	if ($show_subtitles_name_cache ne $tv_show)
	{
		$show_subtitles_season_cache = '';
		$show_subtitles_show_id = '';
		$show_subtitles_page_cache = '';
		#print "page content:\n$subtitles_front_page_cache\n";
		if ($subtitles_front_page_cache =~ m/<a href=\"tvshow-(\d+)-(\d+)\.html"><b>$tv_show/i)
		{
			$show_subtitles_name_cache = $tv_show;
			$show_subtitles_show_id = $1;
			print "Show ID for subtitle is '$show_subtitles_show_id'\n";
		}
		else
		{
			print "Unable to locate show '$tv_show' subtitles page.\n";
			return;
		}
	}
	
	if ($show_subtitles_season_cache ne $season)
	{
		my $show_subtitles_url = "http://www.tvsubtitles.net/tvshow-".$show_subtitles_show_id."-".$season.".html";
		print "Loading season subttitles page from '$show_subtitles_url'\n";
		$show_subtitles_page_cache = FillMythMetadataHttpCaller::get_http_response($show_subtitles_url);
		$show_subtitles_season_cache = $season;
	}	
		
	my $episode_key = $season."x".$episode;
	#print "page content:\n$show_subtitles_page_cache\n";
	if ($show_subtitles_page_cache =~ m/<td>$episode_key<\/td>.*?<a href=\"episode-(\d+)\.html/i)
	{
		my $subs_page_url = "http://www.tvsubtitles.net/episode-".$1.".html";
		print "Download subtitles page for $episode_key from '$subs_page_url'\n";
		my $content = FillMythMetadataHttpCaller::get_http_response($subs_page_url);
		#/subtitle-65387.html
		if ($content =~ m/<a href=\"\/subtitle-(\d+?)\.html\" title=\"Download $subtitles_lang subtitles\"  class=\"subtitle\" style=\"clear:both\">/i)
		{
			my $download_the_subtitle_url = "http://www.tvsubtitles.net/download-".$1.".html";
			print "Download subtitle for $episode_key from '$download_the_subtitle_url'\n";
			system("wget $download_the_subtitle_url -O subtitle.gz");
			system("gzip -d -c -f subtitle.gz >> '$full_subtitle_filename'");
		}
		else
		{
			print "Can not locate $subtitles_lang subtitles!\n";
			return;
		}
	}
	else
	{
		print "Can not locate subtitle for $episode_key!\n";
		return;
	}
}


